import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
	
	public static void usage() {
		System.out.println("usage:Main kernel_root_dir new_project_dir");
	}
    
    @SuppressWarnings("unused")
    private static void saveMakeParam(MakeParam makeParam, File makeParamFile) {
        ObjectOutputStream outputStream = null;
        try {
            outputStream = new ObjectOutputStream(new FileOutputStream(new File("./make_param")));
            outputStream.writeObject(makeParam);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    
    @SuppressWarnings("unused")
    private static MakeParam loadMakeParam(File makeParamFile) {
        ObjectInputStream inputStream = null;
        MakeParam makeParam = null;
        
        try {
            inputStream = new ObjectInputStream(new FileInputStream(makeParamFile));
            Object object = inputStream.readObject();
            if(object == null || !(object instanceof MakeParam)) {
                throw new Exception("Error object:" + object);
            }
            makeParam = (MakeParam)object;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        return makeParam;
    }
    
    public static void main(String[] args) {
        
        if(args.length != 2) {
            usage();
            return;
        }
        
//        String kernelRootDir = "/home/dongbowen/work/openwrt/openwrt/build_dir/target-mips_34kc_uClibc-0.9.33.2/"
//                + "linux-ar71xx_generic/linux-3.18.45/";
//        String newProjectDir = "/home/dongbowen/workspace/linux-3.18.45";
        String kernelRootDir = args[0];
        String newProjectDir = args[1];
        
//        File makeParamFile = new File("./make_param");
        MakeParam makeParam = null;
        
        makeParam = CmdFileParser.parseKernel(new File(kernelRootDir));
//        saveMakeParam(makeParam, makeParamFile);
//        makeParam = loadMakeParam(makeParamFile);
        CmdFileParser.filter(makeParam);
        System.out.println(makeParam);
        
        ProjectCreator projectCreator = new TemplateProjectCreator(kernelRootDir, makeParam, newProjectDir);
        try {
            projectCreator.create();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
